<?php

namespace App\Http\Controllers\CallingCards\Merchant;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\CallingCards\MerchantAppAuth;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseePosterRecord;
use App\Models\FeishuCallingCard\FeishuCallingCardPosterBackground;
use App\Service\CallingCards\MerchantShareImageService;
use App\Service\CallingCards\ShareImageService;
use Illuminate\Http\Request;
use Kuafu\File\FileUtil;

class BackgroundController extends BaseController
{
    public function index()
    {
        $preview     = MerchantAppAuth::$franchisee->wechatPreviewUrl;
        $backgrounds = FeishuCallingCardPosterBackground::query()
            ->where('startDate', '<=', date('Y-m-d'))
            ->where('endDate', '>=', date('Y-m-d'))
            ->where('status', FeishuCallingCardPosterBackground::STATUS_ON)
            ->where('isInternalUse', 0)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get();
        $list = [
            '全部' => [
                'type'  => '全部',
                'items' => [],
            ]
        ];
        if (strlen($preview)) {
            $list['全部'] = [
                'type'  => '全部',
                'items' => [
                    [
                        'id'   => 0,
                        'path' => MerchantAppAuth::$franchisee->backgroundUrl,
                        'url'  => FileUtil::domain() . '/' . $preview . '?x-oss-process=image/resize,h_1334/quality,q_80'
                    ]
                ],
            ];
        }
        foreach ($backgrounds as $background) {
            $list['全部']['items'][] = [
                'id'   => $background->id,
                'path' => $background->imageUrl,
                'url'  => FileUtil::domain() . '/' . $background->previewImageUrl . '?x-oss-process=image/resize,h_1334/quality,q_80'
            ];
        }
        foreach ($backgrounds as $background) {
            $type = strlen($background->type) ? $background->type : '全部';
            if ('全部' == $type) {
                continue;
            }
            if (!isset($list[$type])) {
                $list[$type] = [
                    'type'  => $type,
                    'items' => [],
                ];
            }
            $list[$type]['items'][] = [
                'id'   => $background->id,
                'path' => $background->imageUrl,
                'url'  => FileUtil::domain() . '/' . $background->previewImageUrl . '?x-oss-process=image/resize,h_1334/quality,q_80'
            ];
        }

        $list = array_values($list);
        return $this->success(compact('list'));
    }

    /**
     * 上传自定义背景图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function upload(Request $request)
    {
        $this->validate($request, [
            'url' => 'required|string',
        ]);
        $path = ltrim(parse_url($request->post('url', ''), PHP_URL_PATH));
        MerchantShareImageService::uploadBackground(MerchantAppAuth::$franchisee, $path);
        return $this->success([
            'previewUrl' => FileUtil::domain() . '/' . MerchantAppAuth::$franchisee->wechatPreviewUrl,
            'path'       => MerchantAppAuth::$franchisee->wechatPreviewUrl,
        ]);
    }

    /**
     * 制作分享用的海报
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function makePoster(Request $request)
    {
        $this->validate($request, [
            'id'   => 'required|int|min:0',
            'path' => 'sometimes|string',
        ]);
        // 动态判断path
        $path = '';
        $shopId = (int)$request->header('shopId', 0);
        $id   = $request->post('id', 0);
        if ($id > 0) {
            $background = FeishuCallingCardPosterBackground::find($id);
            if ($background) {
                $path = $background->imageUrl;
            } else {
                $path = ShareImageService::DEFAULT_BG;
            }
        } else {
            $path = ltrim(parse_url($request->post('path', ''), PHP_URL_PATH), '/');
        }
        // 去生成海报
        $arr                                    = MerchantShareImageService::makeShareImage(
            MerchantAppAuth::$userId,
            $path,
            MerchantAppAuth::$userInfo['username'] ?? '',
            MerchantAppAuth::$userInfo['mobile'] ?? '',
            MerchantAppAuth::$franchisee->position,
            ltrim(parse_url(MerchantAppAuth::$userInfo['avatar'], PHP_URL_PATH), '/'),
            $shopId
        );
        MerchantAppAuth::$franchisee->wechatUrl = $arr['path'];
        MerchantAppAuth::$franchisee->backgroundId = $id;
        MerchantAppAuth::$franchisee->save();
        // 记录每次生成日志
        FeishuCallingCardFranchiseePosterRecord::insert([
            'uid'       => MerchantAppAuth::$userId,
            'wechatUrl' => $arr['path'],
            'createdAt' => time(),
            'updatedAt' => time(),
        ]);
        return $this->success($arr);
    }
}
